<template>
  <el-card class="page-order">
    <div slot="header">商品统计</div>
    <div class="search-box">
      时间范围
      <el-date-picker
        size="mini"
        v-model="date"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
      <el-button @click="getData" size="mini" type="primary">查询</el-button>
    </div>
    <chart-bar :chart-data="chartData"></chart-bar>
  </el-card>
</template>

<script>
import {getTotalReq} from '@/api/order'
import {formatYMDhms} from '@/filters'
import * as echarts from 'echarts'
import ChartBar from './ChartBar.vue'
export default {
  components: {
    ChartBar,
  },
  data() {
    return {
      date: [],
      chartData: {},
    }
  },
  methods: {
    async getData() {
      let res = await getTotalReq({
        date: JSON.stringify(this.date),
      })

      //解构数据
      let {data} = res.data
      //处理数据
      let xData = data.map(v => formatYMDhms(v.orderTime))
      let series = [
        {
          type: 'bar',
          name: '金额数据',
          data: data.map(v => v.orderAmount),
        },
      ]

      // 数据赋值
      this.chartData = {xData, series}
      //画图
      // this.renderLine({
      //   xData,
      //   series,
      //   title: '金额图表',
      // })
    },
    //画折线图
    renderLine(obj) {
      //默认值
      let defaultOptions = {
        title: '默认标题',
      }
      let finalObj = {...defaultOptions, ...obj}

      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(this.$refs.chartRef)
      //配置项
      let options = {
        title: {
          text: finalObj.title,
          left: 15,
          top: 15,
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          top: 15,
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: finalObj.xData,
        },
        yAxis: {
          type: 'value',
        },
        series: finalObj.series,
      }
      // 绘制图表
      myChart.setOption(options)
    },
  },
  mounted() {
    this.getData()
  },
}
</script>

<style lang="scss" scoped>
.page-order {
  height: 100%;
  background: #f0f2f5;
}

.myChart {
  margin-top: 50px;
  height: 300px;
  background: white;
}
</style>
